package app.fugema.shop.main.goods.view;

import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import app.fugema.shop.helper.ShareDialogFragment;
import app.fugema.shop.helper.ShareHelper;
import app.fugema.shop.main.evaluate.model.EvaluatePageResult;
import app.fugema.shop.main.evaluate.view.EvaluateGoodsActivity;
import app.fugema.shop.main.evaluate.view.GoodsQuestionActivity;
import app.fugema.shop.main.goods.adapter.CouponTagAdapter;
import app.fugema.shop.main.goods.adapter.MyBannerImageLoader;
import app.fugema.shop.main.goods.adapter.SimilarGoodsAdapter;
import app.fugema.shop.main.goods.model.CouponTagBean;
import app.fugema.shop.main.goods.model.FullDiscountBean;
import app.fugema.shop.main.goods.model.GoodsDetailResult;
import app.fugema.shop.main.goods.model.ShopCouponBean;
import app.fugema.shop.main.goods.model.ShopCouponResult;
import app.fugema.shop.main.goods.model.SimilarGoodsResult;
import app.fugema.shop.main.wallet.model.BuyBean;
import app.fugema.shop.main.wallet.view.WalletPayDialogFragment;

import com.base.common.app.LoginUtils;
import com.base.common.model.http.jackSon.JacksonUtils;
import com.base.common.netBeanPackage.BaseApiResult;
import com.base.common.netBeanPackage.LiveDataWrapper;
import com.base.common.utils.OnClickCheckedUtil;
import com.base.common.utils.RxTimer;
import com.base.common.utils.UIUtils;
import com.base.common.utils.span.SpanUtils;
import com.base.common.view.adapter.MyFlexboxLayoutManager;
import com.base.common.view.adapter.MyGridLayoutManager;
import com.base.common.view.base.BaseActivity;
import com.base.common.view.widget.nineImageView.ImagesActivity;
import com.base.common.viewmodel.BaseViewObserver;
import com.jeremyliao.liveeventbus.LiveEventBus;
import app.fugema.shop.R;
import app.fugema.shop.constants.AppConstants;
import app.fugema.shop.databinding.ActivityGoodsDetailBinding;
import app.fugema.shop.main.evaluate.adapter.EvaluateGoodsItemAdapter;
import app.fugema.shop.main.home.model.GoodsDetailBean;
import app.fugema.shop.main.goods.vm.GoodsVM;
import app.fugema.shop.main.order.model.GroupBookingBean;
import app.fugema.shop.main.order.view.ShoppingCartBottomFragment;

import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.loader.ImageLoaderInterface;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 商品详情  秒杀 拼团
 */
public class GoodsDetailActivity extends BaseActivity<ActivityGoodsDetailBinding, GoodsVM>
{
    /**
     * @param context
     * @param goodsId
     */
    public static void start(Context context, int goodsId)
    {
        Intent intent = new Intent(context, GoodsDetailActivity.class);
        intent.putExtra("goodsId", goodsId);
        context.startActivity(intent);
    }

    public static void start(Context context, GroupBookingBean.RecordsBean goodBean)
    {
        if (goodBean == null) return;
        Intent intent = new Intent(context, GoodsDetailActivity.class);
        intent.putExtra("goodBean", JacksonUtils.transBean2Json(goodBean));
        context.startActivity(intent);
    }


    private int goodsId;
    private int type = 0; // 0商品详情  1秒杀  2拼团

    private EvaluateGoodsItemAdapter adapter;
    private RxTimer rxTimer;
    private boolean isShowPayDialog = false;//是否显示支付弹窗
    private BuyBean buyBean;
    private BigDecimal money;//支付金额

    private GoodsDetailResult.ShopBean shopBean;
    private GoodsDetailResult.ProductBean mProductBean;

    private String userKey = "";
    private CouponTagAdapter couponAdapter;

    private List<ShopCouponBean>  mCouponList;
    //店铺的满减信息
    private FullDiscountBean mFullDiscount;

    private SimilarGoodsAdapter similarAdapter;
    @Override
    protected void onResume()
    {
        super.onResume();
        if (isShowPayDialog)
        {
            isShowPayDialog = false;
            if (buyBean != null)
            {
                // 显示支付 弹出框
                addFragment(WalletPayDialogFragment.newInstance(buyBean));
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_goods_detail);
    }

    @Override
    protected void initNotificationReceipt()
    {
        super.initNotificationReceipt();
        LiveEventBus.get(AppConstants.EventKey.ORDER_CONFIRM_SUCCESS, BuyBean.class).observe(this, new Observer<BuyBean>()
        {
            @Override
            public void onChanged(BuyBean buyBean)
            {
                GoodsDetailActivity.this.buyBean = buyBean;
                isShowPayDialog = true;
            }
        });
    }

    @Override
    protected void initView()
    {
        super.initView();
        binding.ivImageLeftClose.setOnClickListener(new OnClickCheckedUtil() {
            @Override
            public void onClicked(View view) {
                finish();
            }
        });

        binding.tvTitleCenter.setOnClickListener(new OnClickCheckedUtil() {
            @Override
            public void onClicked(View view) {
                titleChange(true);
            }
        });

        //收藏
        binding.tvCollectBtn.setOnClickListener(new OnClickCheckedUtil() {
            @Override
            public void onClicked(View view) {
                //UIUtils.showToastSafes("收藏");
                if(LoginUtils.isLogin() && UIUtils.isNotEmpty( mProductBean ) )
                {
                    viewModel.addFavoriteProduct( mProductBean.getProductId() , userKey )
                             .observe(GoodsDetailActivity.this, new BaseViewObserver<LiveDataWrapper<BaseApiResult>>()
                             {
                                 @Override
                                 protected void onSuccess(LiveDataWrapper<BaseApiResult> data)
                                 {
                                     if( data.data.isSuccess() )
                                     {
                                         changeCollectText(mProductBean);
                                         UIUtils.showToastSafes( data.data.getMsg() );
                                     }
                                 }
                             });
                }
            }
        });
        //分享
        binding.tvShareBtn.setOnClickListener(new OnClickCheckedUtil() {
            @Override
            public void onClicked(View view) {
                /*
                new ShareHelper.LinkBuilder(GoodsDetailActivity.this, "https://www.fugema.cn/")
                        .title(mProductBean.getProductName())
                        .setAdditional(true)
                        .setShowEdit(true)
                        .description(mProductBean.getProductName())
                        .icon("")
                        .setClickListener(new OnClickCheckedUtil() {
                            @Override
                            public void onClicked(View view) {
                            }
                        }).platform(SHARE_MEDIA.ALIPAY).build().share();
                */
                /*
                new ShareHelper.LinkBuilder(GoodsDetailActivity.this, "https://www.fugema.cn/")
                        .title(mProductBean.getProductName())
                        .setAdditional(true)
                        .setShowEdit(true)
                        .description(mProductBean.getProductName())
                        .icon("")
                        .setClickListener(new OnClickCheckedUtil() {
                            @Override
                            public void onClicked(View view) {
                            }
                        }).platform(SHARE_MEDIA.WEIXIN).build().share();
                */

                //UIUtils.showToastSafes("分享");
                StringBuffer productUrl = new StringBuffer();
                productUrl.append( "https://www.fugema.cn/m-WeiXin/Product/Details/");
                productUrl.append( mProductBean.getProductId() );
                addFragment( ShareDialogFragment.shareUrl(GoodsDetailActivity.this,"测试分享", mProductBean.getProductName(),productUrl.toString(),"",null));

            }
        });

        titleChange(true);

        /*
        SpanUtils.with(binding.tvLogisticsDesc).append("物流：").append("现货，预计2-5天送达").setTypeface(Typeface.DEFAULT_BOLD).create();
        SpanUtils.with(binding.tvStoreGuarantee).append("说明：")
                .append("XXX承诺100%正品").setTypeface(Typeface.DEFAULT_BOLD)
                .append("  |  ").setFontSize(DensityUtil.getDimens(R.dimen.dp_14)).setForegroundColor(0xffEEEEEE)
                .append("假一赔三").setTypeface(Typeface.DEFAULT_BOLD)
                .append("  |  ").setFontSize(DensityUtil.getDimens(R.dimen.dp_14)).setForegroundColor(0xffEEEEEE)
                .append("7天无理由退货").setTypeface(Typeface.DEFAULT_BOLD)
                .create();
        */
        // 留言评论
        binding.tvEvaluateMore.setOnClickListener(new OnClickCheckedUtil() {
            @Override
            public void onClicked(View view) {
                EvaluateGoodsActivity.start(getActivity(), goodsId);
            }
        });
        //问问大家
        binding.clAskUsBtn.setOnClickListener(new OnClickCheckedUtil() {
            @Override
            public void onClicked(View view) {
                GoodsQuestionActivity.start(getActivity(), mProductBean );
            }
        });

        adapter = new EvaluateGoodsItemAdapter();
        binding.rvRecyclerEvaluate.setAdapter(adapter);

        //进入店铺
        binding.tvBtnInStore.setOnClickListener(new OnClickCheckedUtil() {
            @Override
            public void onClicked(View view) {

                if( UIUtils.isNotEmpty( shopBean ) )
                {
                    ShopActivity.start(GoodsDetailActivity.this,shopBean.getVShopId());
                }
            }
        });
        //店铺关注
        binding.tvBtnCollect.setOnClickListener(new OnClickCheckedUtil() {
            @Override
            public void onClicked(View view) {
                //UIUtils.showToastSafes("关注店铺");
                if(LoginUtils.isLogin() && UIUtils.isNotEmpty( shopBean ) )
                {
                    viewModel.addFavoriteShop(shopBean.getVShopId(),userKey)
                             .observe(GoodsDetailActivity.this, new BaseViewObserver<LiveDataWrapper<BaseApiResult>>()
                             {
                                 @Override
                                 protected void onSuccess(LiveDataWrapper<BaseApiResult> data)
                                 {
                                     //{"success":true,"msg":"取消成功","code":0}
                                     if( data.data.isSuccess() )
                                     {
                                         changeShopCollectText(shopBean);
                                         UIUtils.showToastSafes( data.data.getMsg() );
                                     }

                                 }
                             });
                }
            }
        });
        // 显示的优惠券 等
        couponAdapter = new CouponTagAdapter();

        couponAdapter.setOnItemClickInterface((view, onclickType, itemType, position, bean) -> {
            // 点击 显示 优惠券弹出框
            showCouponListDialog(mCouponList);
            return false;
        });

        binding.rvCouponList.setLayoutManager(new MyFlexboxLayoutManager(this));
        binding.rvCouponList.setAdapter( couponAdapter );
        // 点击 显示 优惠券弹出框
        binding.tvCouponTag.setOnClickListener(new OnClickCheckedUtil() {
            @Override
            public void onClicked(View view) {
                showCouponListDialog(mCouponList);
            }
        });

        //6个 推荐商品
        MyGridLayoutManager mGridLayoutMgr = new MyGridLayoutManager(this, 2);
        binding.rvSimilarList.setLayoutManager(mGridLayoutMgr);
        similarAdapter = new SimilarGoodsAdapter();
        binding.rvSimilarList.setAdapter( similarAdapter );
    }


    private void titleChange(boolean isGoods)
    {
        if (isGoods)
        {
            binding.tvTitleCenter.setTextColor(0xffffffff);
            //binding.tvTitleCenter.setTypeface(Typeface.DEFAULT_BOLD);

            //binding.tvTextRight.setTextColor(0xff999999);
           // binding.tvTextRight.setTypeface(Typeface.DEFAULT);
            binding.nsvScrollView.scrollTo(0, 0);
        } else {
            //binding.tvTextRight.setTextColor(0xff333333);
            //binding.tvTextRight.setTypeface(Typeface.DEFAULT_BOLD);

            binding.tvTitleCenter.setTextColor(0xffffffff);
            binding.tvTitleCenter.setTypeface(Typeface.DEFAULT);

            int y = binding.llGoodsDetail.getTop();

            binding.nsvScrollView.scrollTo(0, y);
        }
    }


    @Override
    protected void initData(Intent intent)
    {
        super.initData(intent);
        //满减信息
        binding.llDiscountLayout.setVisibility(View.VISIBLE);
        //优惠券
        binding.llCoupon.setVisibility(View.VISIBLE);

        if(LoginUtils.isLogin())
        {
            userKey = LoginUtils.getToken();
        }

        String goodsStr = intent.getStringExtra("goodBean");
        //根据 id 查商品信息
        if (UIUtils.isEmpty(goodsStr))
        {
            goodsId = intent.getIntExtra("goodsId", 0);
            type = 0;
            binding.clTitleOne.setVisibility(View.GONE);
            binding.clTitleTwo.setVisibility(View.GONE);
            binding.clPrice.setVisibility(View.VISIBLE);
            binding.llGroupBooking.setVisibility(View.GONE);//拼团
            //查商品信息
            viewModel.getProductDetail(goodsId ,userKey)
                     .observe(this, new BaseViewObserver<LiveDataWrapper<GoodsDetailResult>>(this)
                     {
                            @Override
                            protected void onSuccess(LiveDataWrapper<GoodsDetailResult> data)
                            {
                                GoodsDetailResult goodsDetail =  data.data;
                                mProductBean = goodsDetail.getProduct();
                                shopBean = goodsDetail.getShop();
                                mFullDiscount = goodsDetail.getFullDiscount();
                                // 设置 页面信息
                                setDataValues(goodsDetail);
                                money =  BigDecimal.valueOf( mProductBean.getMinSalePrice() ) ;
                                binding.flBottom.setVisibility(View.VISIBLE);
                                ShoppingCartBottomFragment fragment = (ShoppingCartBottomFragment) getSupportFragmentManager().findFragmentById(R.id.shoppingCart);
                                if (fragment != null)
                                {
                                    fragment.setDataBean(goodsDetail);
                                }
                                queryShopCoupon( shopBean );

                                queryDetailSimilayProducts(goodsId);
                            }

                            @Override
                            public boolean isEmptyData(LiveDataWrapper<GoodsDetailResult> data)
                            {
                                return UIUtils.isEmpty(data.data.getProduct());
                            }
            });

        } else {
            // 有商品信息时
            binding.clTitleOne.setVisibility(View.VISIBLE);
            binding.clTitleTwo.setVisibility(View.VISIBLE);
            binding.clPrice.setVisibility(View.GONE);
            binding.flBottom.setVisibility(View.GONE);
            binding.rtvPay.setVisibility(View.VISIBLE);
            GroupBookingBean.RecordsBean goodBean = JacksonUtils.getJsonBean(goodsStr, GroupBookingBean.RecordsBean.class);
            if (goodBean != null) {
                GoodsDetailBean.DataBean dataBean = new GoodsDetailBean.DataBean();
                dataBean.setImgs(goodBean.getImgs());
                dataBean.setContent(goodBean.getContent());
                dataBean.setBrief(goodBean.getBrief());
                dataBean.setCategoryId(goodBean.getCategoryId());
                dataBean.setShopId(goodBean.getShopId());
                dataBean.setShopName(goodBean.getShopName());
                dataBean.setProdId(goodBean.getProdId());
                dataBean.setProdName(goodBean.getProdName());
                dataBean.setPrice(goodBean.getPrice());
                dataBean.setOriPrice(goodBean.getOriPrice());
                dataBean.setPic(goodBean.getPic());
                dataBean.setSaleCount(goodBean.getSaleCount());

                //setDataValues(dataBean);
                binding.flBottom.setVisibility(View.GONE);


                type = goodBean.getSkId() == 0 ? 2 : 1;// 0商品详情  1秒杀  2拼团
                money = goodBean.getPrice();
                if (type == 1) {
                    binding.tvTimeText.setText("限时秒杀");
                    binding.rtvTitleFlag.setText("商品\n秒杀");
                    binding.llGroupBooking.setVisibility(View.GONE);//拼团
                } else {
                    binding.tvTimeText.setText("限时拼团");
                    binding.rtvTitleFlag.setText("商品\n拼团");
                    binding.llGroupBooking.setVisibility(View.GONE);//拼团
                    binding.rtvPay.setText("立即参团");
                }
                binding.rtvPay.setOnClickListener(new OnClickCheckedUtil() {
                    @Override
                    public void onClicked(View view) {
                        if (type == 1) {
                            skills(goodBean);
                        } else {
                            bookingGroup(goodBean);
                        }
                    }
                });
                if (rxTimer == null)
                {
                    rxTimer = new RxTimer();
                }
                else
                {
                    rxTimer.cancel();
                }

                rxTimer.interval(1000, new RxTimer.RxAction() {
                    @Override
                    public void action(long number) {
                        binding.rtvTimeHour.setText(goodBean.getTimeHour());
                        binding.rtvTimeMinute.setText(goodBean.getTimeMinute());
                        binding.rtvTimeSecond.setText(goodBean.getTimeSecond());
                    }
                });
            }
        }

        //查商品 第一条 评论
        viewModel.getGoodsEvaluate(goodsId).observe(this, new BaseViewObserver<LiveDataWrapper<EvaluatePageResult>>(this)
        {
            @Override
            protected void onSuccess(LiveDataWrapper<EvaluatePageResult> data)
            {
                binding.llEvaluate.setVisibility(View.VISIBLE);
                adapter.setDataList(data.data.getData());
            }

            @Override
            public boolean isEmptyData(LiveDataWrapper<EvaluatePageResult> data)
            {
                return UIUtils.isEmpty(data.data.getData());
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode,resultCode,data);
    }

    @Override
    public void onDestroy()
    {
        super.onDestroy();
        if (rxTimer != null) {
            rxTimer.cancel();
        }
    }


    //秒杀
    private void skills(GroupBookingBean.RecordsBean goodBean)
    {

    }

    //拼团
    private void bookingGroup(GroupBookingBean.RecordsBean goodBean)
    {
        UIUtils.showToastSafes("拼团成功");
    }

    // 设置页面信息
    private void setDataValues(GoodsDetailResult detailBean)
    {
        binding.setItem(detailBean);
        if (UIUtils.isNotEmpty(detailBean.getProduct().getImagePath()))
        {
            List<String> imageList = detailBean.getProduct().getImagePath();

            ImageLoaderInterface mImageLoader = new MyBannerImageLoader();

            binding.banner.setImages(imageList).setImageLoader(mImageLoader).setDelayTime(3000).start();
            binding.banner.setOnBannerListener(new OnBannerListener() {
                @Override
                public void OnBannerClick(int position) {
                    ImagesActivity.startActivity(((MyBannerImageLoader) mImageLoader).getImageViewList().get(position), imageList,position);
                }
            });

        }
        else
        {
            binding.cllImages.setVisibility(View.GONE);
        }

        String saleStr = getString( R.string.sales_count );
        SpanUtils.with(binding.tvLogisticsDesc).append(String.format(saleStr , String.valueOf( detailBean.getSaleCounts() )))
                                               .append("  "+detailBean.getFreightStr())
                                               .append("  "+detailBean.getSendTime())
                                               .create();

        binding.tvStoreGuarantee.setText( detailBean.getProductAddress() );
        /*
        SpanUtils.with(binding.tvStoreGuarantee).append("说明：")
                .append("XXX承诺100%正品").setTypeface(Typeface.DEFAULT_BOLD)
                .append("  |  ").setFontSize(DensityUtil.getDimens(R.dimen.dp_14)).setForegroundColor(0xffEEEEEE)
                .append("假一赔三").setTypeface(Typeface.DEFAULT_BOLD)
                .append("  |  ").setFontSize(DensityUtil.getDimens(R.dimen.dp_14)).setForegroundColor(0xffEEEEEE)
                .append("7天无理由退货").setTypeface(Typeface.DEFAULT_BOLD)
                .create();
        */

        if(shopBean.isIsFavorite())
        {
            binding.tvBtnCollect.setText("已关注");
        }
        else
        {
            binding.tvBtnCollect.setText("关注");
        }
        //binding.reRichEditor.loadDataWithBaseURL( detailBean.getProduct().getProductDescription(),"text/html", "utf-8", null  );
        //binding.reRichEditor.getNewContent(  )
        binding.reRichEditor.loadRichEditorCode(  detailBean.getProduct().getProductDescription() );
        binding.executePendingBindings();
    }

    //根据店铺信息查询优惠券
    private void queryShopCoupon(GoodsDetailResult.ShopBean mShop  )
    {
         viewModel.getShopCouponListByShopId(mShop.getId(),userKey)
                  .observe(this, new BaseViewObserver<LiveDataWrapper<ShopCouponResult>>()
                  {
                      @Override
                      protected void onSuccess(LiveDataWrapper<ShopCouponResult> data)
                      {
                          if( data.data.isSuccess() )
                          {
                              mCouponList = data.data.getCoupon();
                              List<CouponTagBean> tagList = getTagListByCouponResult( data.data.getCoupon() );

                              if( mShop.getFreeFreight() > 0 )
                              {
                                  CouponTagBean freightTag = new CouponTagBean();
                                  freightTag.setCouponContent( new StringBuffer().append("满").append( mShop.getFreeFreight() ).append("元包邮").toString() );
                                  freightTag.setAmount( mShop.getFreeFreight() );
                                  tagList.add( freightTag );
                              }
                              couponAdapter.setDataList(tagList);
                          }
                      }
                  });

    }

    private List<CouponTagBean> getTagListByCouponResult(List<ShopCouponBean> couponBeanList)
    {
        List<CouponTagBean> tagList = new ArrayList<>();

        if( UIUtils.isNotEmpty( couponBeanList ) )
        {
            for (ShopCouponBean tempShopCoupon : couponBeanList)
            {
                CouponTagBean tag = new CouponTagBean();
                tag.setCouponContent( new StringBuffer().append( tempShopCoupon.getPrice() ).append("元优惠券").toString() );
                tag.setAmount( tempShopCoupon.getPrice() );
                tagList.add( tag );
            }
        }
        return tagList;
    }
    // 设置 收藏
    private void changeCollectText(GoodsDetailResult.ProductBean productBean)
    {
        productBean.setIsFavorite( !productBean.isIsFavorite()  );
        if( productBean.isIsFavorite() )
        {
            binding.ivCollectBtn.setImageResource(R.mipmap.ic_collect);
            binding.tvCollectText.setText("已收藏");
        }
        else
        {
            binding.ivCollectBtn.setImageResource(R.mipmap.ic_uncollect);
            binding.tvCollectText.setText("收藏");
        }
    }

    // 设置 店铺 关注文字
    private void changeShopCollectText(GoodsDetailResult.ShopBean mShopBean)
    {
        mShopBean.setIsFavorite( !mShopBean.isIsFavorite() );
        if( mShopBean.isIsFavorite() )
        {
            binding.tvBtnCollect.setText("已关注");
        }
        else
        {
            binding.tvBtnCollect.setText("关注");
        }
    }

    //打开 优惠券列表
    private void showCouponListDialog(List<ShopCouponBean> couponBeanList)
    {
        addFragment( ShopCouponDialogFragment.getInstance( couponBeanList ,shopBean.getFreeFreight(), mFullDiscount )  );
    }

    /**
     * 查询相似商品
     * @param productId
     */
    private void queryDetailSimilayProducts( int productId )
    {
        viewModel.getDetailSimilarProduct( productId )
                 .observe(this, new BaseViewObserver<LiveDataWrapper<SimilarGoodsResult>>()
                 {
                     @Override
                     protected void onSuccess(LiveDataWrapper<SimilarGoodsResult> data)
                     {
                         if( data.data.isSuccess() && UIUtils.isNotEmpty( data.data.getData() ) )
                         {
                             binding.llSimilarView.setVisibility(View.VISIBLE);
                             similarAdapter.setDataList( data.data.getData() );
                         }
                     }
                 });
    }

}
